<?php

namespace Wechat\Controller;

class UserCenterController extends CommonController {

    public function index() {

        $waitingMap["status"] = C("ORDER_STATUS.WAITING_OPEN");
        $waitingMap["customer_id"] = $this->customer["customer_id"];

        $waitingCount = D("Order")
            ->where($waitingMap)
            ->count();

        $this->customer["total_assets"] = sprintf("%.2f"
            , $this->customer["total_assets"]);

        $this->assign("waitingCount", $waitingCount);
        $this->assign("customer", $this->customer);
        $this->display("index");
    }


    public function myWallet() {

        $map["customer_id"] = $this->customer["customer_id"];

        $list = D("Withdraw")
            ->where($map)
            ->order("withdraw_id desc")
            ->select();

        $this->customer["total_assets"] = sprintf("%.2f"
            , $this->customer["total_assets"]);

        $this->assign("statusEnum", C("WITHDRAW_STATUS"));
        $this->assign("list", $list);
        $this->assign("customer", $this->customer);
        $this->display("myWallet");

    }

    public function historyRecordList() {

        $pageNum = I("post.pageNum") ? I("post.pageNum") : 1;

        $groupMap["g.status"] = array("in", array(
            C("GROUP_STATUS.WIN"),
            C("GROUP_STATUS.FAILURE")
        ));

        $groupMap["gm.customer_id"] = $this->customer["customer_id"];

        $groupList = D('GroupMember')->alias('gm')
            ->join("LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id")
            ->join("LEFT JOIN __GROUP__ g on g.group_id = gm.group_id")
            ->join("left join __ROUND__ r on r.round_id = g.round_id")
            ->field('r.round_index,g.status,r.winner_customer_id, c.customer_id, c.nickname,g.round_id,g.customer_id as group_customer_id,
                    g.group_id, g.member_number, g.buy_number, g.reward')
            ->where($groupMap)
            ->order("g.create_time desc")
            ->limit(($pageNum-1)*C("DEFAULT_PAGE_SIZE"), C("DEFAULT_PAGE_SIZE"))
            ->select();

        foreach ($groupList as &$group) {
            $memberMap['gm.group_id'] = $group['group_id'];
            $group['member_list'] = D('GroupMember')->alias('gm')
                ->join('LEFT JOIN __CUSTOMER__ c ON gm.customer_id = c.customer_id')
                ->field("c.customer_id,c.nickname, c.headimgurl, IF(gm.customer_id = " .$group['group_customer_id']. ",1,0) AS is_leader")
                ->where($memberMap)
                ->order("is_leader DESC, gm.number DESC")
                ->limit(4)
                ->select();

            if($group["status"] == C("GROUP_STATUS.WIN")) {
                $countMap['round_id'] = $group['round_id'];
                $countMap['status'] = C('GROUP_STATUS.FAILURE');
                $group['failure_count'] = D('Group')->where($countMap)->count();
                $group["winner_group_id"] = $group["group_id"];
            } else {
                $winnerGroup = D("GroupMember")->alias("gm")
                    ->join("left join __GROUP__ g on g.group_id = gm.group_id")
                    ->where(array(
                        "g.status" => C("GROUP_STATUS.WIN"),
                        "g.round_id" => $group["round_id"],
                        "gm.customer_id" => $group["winner_customer_id"]
                    ))->field("gm.group_id")->find();
                $group["winner_group_id"] = $winnerGroup["group_id"];
            }

        }

        $data["code"] = 200;
        $data['groupList'] = $groupList;

        echo json_encode($data);

    }

    public function historyRecord() {

        $map["gm.customer_id"] = $this->customer["customer_id"];

        $map["g.status"] = C("GROUP_STATUS.WIN");
        $winCount = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($map)
            ->count();

        $map["g.status"] = C("GROUP_STATUS.FAILURE");
        $failureCount = D("GroupMember")->alias("gm")
            ->join("left join __GROUP__ g on g.group_id = gm.group_id")
            ->where($map)
            ->count();

        $rewardMap["r.winner_customer_id"] = $this->customer["customer_id"];
        $rewardCount = D("Round")->alias("r")
            ->where($rewardMap)
            ->count();

        $this->assign("winCount", $winCount);
        $this->assign("failureCount", $failureCount);
        $this->assign("rewardCount", $rewardCount);

        $this->display("historyRecord");

    }

    public function historyBill() {

        $map["customer_id"] = $this->customer["customer_id"];

        $list = D("AccountDetail")
            ->where($map)
            ->order("detail_id desc")
            ->select();

        $tmpTime = date('Y年m月',
            strtotime($list[0]["create_time"]));

        $returnArray = array();
        $monthArray = array();

        foreach ($list as &$item) {

            $item["time"] = date('Y年m月',
                strtotime($item["create_time"]));

            if($tmpTime == $item["time"]) {
                array_push($monthArray, $item);
            } else {
                $returnArray[$tmpTime] = $monthArray;
                $monthArray = array();
                $tmpTime = $item["time"];
                array_push($monthArray, $item);
            }

        }
        if(!isNullOrEmpty($list)) {
            $returnArray[$tmpTime] = $monthArray;
        }

        $this->assign("typeEnum", C("ACCOUNT_DETAIL_TYPE"));
        $this->assign("list", $returnArray);
        $this->display("historyBill");
    }

    public function applyWithdraw() {
        $this->display("applyWithdraw");
    }

    public function apply() {

        $data["code"] = 200;

        $money = I("post.money");

        if($money <= 0) {
            $data["code"] = -1;
            $data["msg"] = "对不起，您的余额不足";
            echo json_encode($data);
            exit();
        }

        if($money > $this->customer["available_assets"]) {
            $data["code"] = -2;
            $data["msg"] = "对不起，您的余额不足";
            echo json_encode($data);
            exit();
        }

        //新增一条提现记录
        $withdrawData["customer_id"] = $this->customer["customer_id"];
        $withdrawData["create_time"] = getCurrentDate();
        $withdrawData["money"] = $money;
        $withdrawData["status"] = C("WITHDRAW_STATUS.WAITING");

        $withdrawId = D("Withdraw")->add($withdrawData);

        //用户总资产转移到冻结资产
        $this->customer["frozen_assets"]
            = $this->customer["frozen_assets"] + $money;
        $this->customer["available_assets"]
            = $this->customer["available_assets"] - $money;

        D("Customer")->updateInfo($this->customer);

        // $arr = array(
        //     'mch_appid' => C('appid'),
        //     'mchid' => C('mch_id'),
        //     'nonce_str' => $this->createNoncestr(),
        //     'partner_trade_no' => time() . rand(0, 999),
        //     'openid' => $this->customer["openid"], //订单号
        //     'check_name' => 'NO_CHECK',
        //     'amount' => $money*100,
        //     'desc' => '申请提现', //通知地址
        //     'spbill_create_ip' => get_client_ip(),
        // );

        // $arr['sign'] = $this->getSign($arr);  //签名

        // $post = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers', $this->arrayToXml($arr));

        // $arr2 = $this->xmlToArray($post);

        // if($arr2['return_code']=='SUCCESS'
        //     && $arr2['result_code'] == 'SUCCESS') {

        //     $withdraw = D("Withdraw")->queryById($withdrawId);

        //     //修改状态
        //     $withdraw["status"] = C("WITHDRAW_STATUS.END");
        //     D("Withdraw")->updateInfo($withdraw);

        //     //增加流水
        //     $accountDetailData["money"] = $withdraw["money"]*(-1);
        //     $accountDetailData["customer_id"] = $withdraw["customer_id"];
        //     $accountDetailData["create_time"] = getCurrentDate();
        //     $accountDetailData["type"] = C("ACCOUNT_DETAIL_TYPE.WITHDRAW");
        //     $accountDetailData["refer_id"] = $withdraw["withdraw_id"];
        //     D("AccountDetail")->add($accountDetailData);

        //     //减用户余额
        //     $this->customer["total_assets"]
        //         = $this->customer["total_assets"] - $withdraw["money"];
        //     $this->customer["frozen_assets"]
        //         = $this->customer["frozen_assets"] - $withdraw["money"];
        //     D("Customer")->updateInfo($this->customer);

        // } else {

        //     $data["code"] = -1;
        //     $data["msg"] = "申请成功，等待客服处理";

        // }

        $data["code"] = -1;
        $data["msg"] = "申请成功，等待客服处理";

        echo json_encode($data);

    }

    function curl_post_ssl($url, $vars, $second=30,$aHeader=array()) {

        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        //以下两种方式需选择一种

        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert-2/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'//cert-2/apiclient_key.pem');

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);
        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }


    /**
     * 	作用：生成签名
     */
    public function getSign($Obj) {

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    /**
     * 	作用：array转xml
     */
    function arrayToXml($arr) {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml.="<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml.="<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml.="</xml>";
        return $xml;
    }

    function signature() {
        $Obj['jsapi_ticket'] = jsapi_ticket();
        $Obj['noncestr'] = createNoncestr();
        $Obj['url'] = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
        $Obj['timestamp'] = time();

        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        //dump($Parameters);
        $String = formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        //$String = $String."&key=".C('mch_key');
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = sha1($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        //$Obj['signature'] = strtoupper($String);
        $Obj['signature'] = $String;

        return $Obj;
    }

    /**
     * 	作用：产生随机字符串，不长于32位
     */
    public function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str.= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 	作用：将xml转为array
     */
    public function xmlToArray($xml) {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

}